import {
    TouchableHighlight,
    View,
    Text,
    Button,
    TextInput,
    ScrollView,
    Alert
} from 'react-native';
import React, {Component} from 'react';
import {Divider, CheckBox, Icon, BottomSheet, ListItem} from '@rneui/themed';
import PasswordEncoder from '../api/PasswordEncoder';
import config from 'react-native-config';
import {SafeAreaProvider} from 'react-native-safe-area-context';
import organizationDomain from '../api/organizationDomain';
import authentication from '../api/authentication';

export default class Login extends Component {
    constructor(props) {44
        super(props);
        this.state = {
            rememberMe: false,
            account: '',
            password: '',
            organizationDomain: {name: '默认组织域', code: 'Default'},
            organizationDomainVisable: false,
            organizationDomains: [{name: '默认组织域', code: 'Default'}],
        };
        this.passwordInput = React.createRef();
        this.login = this.login.bind(this);
        this.getDomaninsByAccount = this.getDomaninsByAccount.bind(this);
        this.forgotPassword = this.forgotPassword.bind(this);
    }

    async componentDidMount() {
        //记住账号
        let remenberedAccount = await storage.get("account")
        if (StrUtils.isNotNull(remenberedAccount)) {
            this.setState({
                account: remenberedAccount,
                rememberMe: true
            })
        }
        if(config.ENABLE_ORGANIZATION_DOMAIN === "true"){
            //请求组织域
            await this.getDomaninsByAccount(remenberedAccount);
        }
    }

    async getDomaninsByAccount(account) {
        if(StrUtils.isEmpty(account)){
            return;
        }
        try {
            let allDomains = await organizationDomain.getLoginDomainsByAccount(account);
            this.setState({
                organizationDomains: allDomains
            })
        } catch (e) {
            Alert.alert(e.message,e.content);
        }
    }

    async login() {
        //校验账密
        if(StrUtils.isEmpty(this.state.account) || StrUtils.isEmpty(this.state.password)){
            Alert.alert("请输入用户密码！");
            return;
        }
        //记住账号(用户名、密码)
        let remenberedAccount =  await storage.get("account")
        if(this.state.rememberMe){
            if(StrUtils.isNull(remenberedAccount)){
                storage.set("account",this.state.account);
            }
            if(StrUtils.isNotNull(remenberedAccount)&&!StrUtils.equals(this.state.account,remenberedAccount)){
                await storage.remove("account");
                storage.set("account",this.state.account);
            }
            storage.set("account",this.state.account);
        }else{
            if(StrUtils.isNotNull(remenberedAccount)){
                await storage.remove("account");
            }
        }
        let loginParam = {
            domainCode: this.state.organizationDomain.code,
            account: this.state.account,
            password: this.state.password,
            rememberMe: this.state.rememberMe
        };
        let loginSuccess = await authentication.login(this, loginParam);
        if(!loginSuccess){
            return;
        }
        //获取个人信息及权限
        let userInfo = await authentication.getCurrentUser(this,this.state.account);
        if(!userInfo){
            return;
        }

        //获取更新

        //获取菜单
        this.props.navigation.navigate('Drawer');
    }

    forgotPassword() {
        this.props.navigation.navigate('ForgotPassword');
    }

    render() {
        const nowDate = new Date();
        let _this = this;
        return (
            <SafeAreaProvider>
                <View
                    style={{
                        height: '100%',
                    }}>
                    <View
                        style={{
                            alignItems: 'center',
                            justifyContent: 'center',
                            height: '30%',
                        }}>
                        <Text
                            style={{
                                fontWeight: 'bold',
                                color: '#262626',
                                fontSize: 24,
                                padding: 5,
                            }}>
                            {config.PROJECT_NAME}
                        </Text>
                        <Text style={{color: '#00000072', fontSize: 10, padding: 5}}>
                            {config.CUSTOMER_NAME}
                        </Text>
                    </View>
                    <ScrollView>
                        <View
                            style={{
                                alignItems: 'center',
                                justifyContent: 'center',
                            }}>
                            <View
                                style={{
                                    width: '60%',
                                    margin: '1%',
                                    flexDirection: 'row',
                                    justifyContent: 'center',
                                    alignItems: 'center',
                                    borderWidth: 1,
                                    borderColor: '#00000072',
                                    height: 28,
                                }}>
                                <Icon
                                    name="user"
                                    size={16}
                                    color={'#00000072'}
                                    type="antdesign"
                                    style={{marginLeft: 3, marginRight: 3}}
                                />
                                <TextInput
                                    style={{
                                        width: '100%',
                                        height: '100%',
                                        borderWidth: 0,
                                        flex: 1,
                                        padding: 0,
                                    }}
                                    autoFocus={true}
                                    value={this.state.account}
                                    onChangeText={value => {
                                        this.getDomaninsByAccount(value);
                                        this.setState({
                                            account: value,
                                        });
                                    }}
                                    onSubmitEditing={() => {
                                        _this.passwordInput.current.focus();
                                    }}
                                />
                            </View>
                            <View
                                style={{
                                    width: '60%',
                                    margin: '1%',
                                    flexDirection: 'row',
                                    justifyContent: 'center',
                                    alignItems: 'center',
                                    borderWidth: 1,
                                    borderColor: '#00000072',
                                    height: 28,
                                }}>
                                <Icon
                                    name="lock"
                                    size={18}
                                    color={'#00000072'}
                                    type="antdesign"
                                    style={{marginLeft: 3, marginRight: 3}}
                                />
                                <TextInput
                                    ref={this.passwordInput}
                                    style={{
                                        width: '100%',
                                        height: '100%',
                                        borderWidth: 0,
                                        flex: 1,
                                        padding: 0,
                                    }}
                                    autoFocus={false}
                                    value={this.state.password}
                                    onChangeText={value => {
                                        this.setState({
                                            password: value,
                                        });
                                    }}
                                    secureTextEntry={true}
                                    onSubmitEditing={() => {
                                        _this.login();
                                    }}
                                />
                            </View>
                            {config.ENABLE_ORGANIZATION_DOMAIN === "true" ? (
                                <View style={{width: '60%', margin: '1%'}}>
                                    <TouchableHighlight
                                        onPress={() => {
                                            this.setState({
                                                organizationDomainVisable: true,
                                            });
                                        }}
                                        style={{
                                            borderWidth: 1,
                                            borderColor: '#00000072',
                                            padding: 2,
                                            height: 28,
                                        }}
                                        underlayColor="#f5f5f5">
                                        <View
                                            style={{
                                                flexDirection: 'row',
                                            }}>
                                            <Text
                                                style={{
                                                    fontSize: 16,
                                                    flex: 1,
                                                }}>
                                                {this.state.organizationDomain.name}
                                            </Text>
                                            <Icon
                                                size={16}
                                                name={
                                                    this.state.organizationDomainVisable ? 'up' : 'down'
                                                }
                                                color={'#00000072'}
                                                type="antdesign"
                                                style={{margin: 2}}
                                            />
                                        </View>
                                    </TouchableHighlight>
                                </View>
                            ) : null}

                            <View
                                style={{
                                    width: '60%',
                                    margin: '1%',
                                    flexDirection: 'row',
                                    justifyContent: 'space-between',
                                    alignItems: 'center',
                                }}>
                                <View>
                                    <CheckBox
                                        size={20}
                                        center={true}
                                        checked={this.state.rememberMe}
                                        onPress={() => {
                                            this.setState({
                                                rememberMe: !this.state.rememberMe,
                                            });
                                        }}
                                        title="记住我"
                                        iconType="material-community"
                                        checkedIcon="checkbox-marked"
                                        uncheckedIcon="checkbox-blank-outline"
                                        checkedColor="red"
                                        containerStyle={{
                                            padding: 0,
                                            marginLeft: -2,
                                            marginRight: 0,
                                            marginTop: -3,
                                            marginBottom: -3,
                                        }}
                                        textStyle={{
                                            marginLeft: 0,
                                            marginRight: 0,
                                            fontSize: 12,
                                            backgroundColor: '#f5f5f5',
                                        }}
                                        wrapperStyle={{
                                            backgroundColor: '#f5f5f5',
                                        }}
                                    />
                                </View>
                                <View>
                                    <TouchableHighlight
                                        onPress={() => {
                                            this.forgotPassword();
                                        }}
                                        underlayColor="#f5f5f5">
                                        <Text
                                            style={{
                                                flex: 1,
                                                fontSize: 12,
                                                color: '#2089dc',
                                                fontWeight: 'bold',
                                            }}>
                                            忘记密码
                                        </Text>
                                    </TouchableHighlight>
                                </View>
                            </View>
                            <View style={{width: '60%', margin: '1%'}}>
                                <Button
                                    title="登录"
                                    onPress={this.login}
                                    buttonStyle={{
                                        backgroundColor: '#2089dc',
                                        borderRadius: 30,
                                    }}
                                />
                            </View>
                        </View>
                    </ScrollView>

                    <View style={{height: 20, width: '100%', alignItems: 'center'}}>
                        <Divider style={{width: '100%'}}/>
                        <View style={{flexDirection: 'row'}}>
                            <View style={{flex: 1, alignItems: 'center'}}>
                                <Text style={{fontSize: 10}}>
                                    {config.COPY_RIGHT.replace('${year}', nowDate.getFullYear())}V
                                    {config.VERSION}
                                </Text>
                            </View>
                            <TouchableHighlight
                                style={{margin: 2}}
                                onPress={() => {
                                    this.props.navigation.navigate('ForgotPassword');
                                }}
                                underlayColor="#f5f5f5">
                                <Icon
                                    size={10}
                                    name="settings"
                                    color={'#00000072'}
                                    type="feather"
                                />
                            </TouchableHighlight>
                        </View>
                    </View>
                    <BottomSheet
                        modalProps={{animationType: 'slide'}}
                        onBackdropPress={() => {
                            _this.setState({
                                organizationDomainVisable: false,
                            });
                        }}
                        isVisible={this.state.organizationDomainVisable}>
                        {this.state.organizationDomains.map((organizationDomain, index) => (
                            <ListItem
                                key={index}
                                containerStyle={{
                                    backgroundColor: this.state.organizationDomain
                                        ? organizationDomain.code ===
                                        this.state.organizationDomain.code
                                            ? '#e8e8e8'
                                            : 'white'
                                        : 'white',
                                    borderWidth: 1,
                                    borderColor: 'white',
                                }}
                                onPress={() => {
                                    _this.setState({
                                        organizationDomainVisable: false,
                                        organizationDomain: organizationDomain,
                                    });
                                }}>
                                <ListItem.Content>
                                    <ListItem.Title style={{color: '#262626'}}>
                                        {organizationDomain.name}
                                    </ListItem.Title>
                                </ListItem.Content>
                            </ListItem>
                        ))}
                    </BottomSheet>
                </View>
            </SafeAreaProvider>
        );
    }
}
